import subprocess
import time
import webbrowser
import requests
import tkinter
import tkinter.messagebox
import archive_test
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys

# project_name = 'ztjyyd'    # 项目名称
# archive_workspace_path = '/Users/wangxiaojin/Desktop/ztjyyd/Source/ZTJYYD'    # 项目路径
# export_directory = '/Users/wangxiaojin/Desktop/ipa_exportFile'    # 输出的文件夹
exportOptionsPath = 'ExportOptions.plist'  # ExportOptions.plist 文件


class AutoArchive(object):

    def __init__(self):
        pass

    def modifyFilePath(self, filePath):
        if 'file://' in filePath:
            return filePath[7:]
        return filePath

    def clean(self, export_directory, archive_workspace_path,project_name, isContinue):
        print('\n\n ==============clean=============')
        if archive_workspace_path.lenth == 0:
            print('\n\n ========archive_workspace_path is nil=============')
            return
        if export_directory.lenth == 0 :
            print('\n\n ========export_directory is nil=============')
            return

        archive_workspace_path = self.modifyFilePath(archive_workspace_path)
        export_directory  = self.modifyFilePath(export_directory)

        start = time.time()
        clean_cmd = 'xcodebuild clean -workspace %s/%s.xcworkspace -scheme %s -configuration Release' % (
            archive_workspace_path, project_name, project_name)
        clean_command_run = subprocess.Popen(clean_cmd, shell=True)
        clean_command_run.wait()
        end = time.time()
        # Code码
        clean_result_code = clean_command_run.returncode
        if clean_result_code != 0:
            print("=======clean失败,用时:%.2f秒=======" % (end - start))
        else:
            print("=======clean成功,用时:%.2f秒=======" % (end - start))
            if isContinue :
                self.build(export_directory,archive_workspace_path, project_name , isContinue)

    def build(self,export_directory, archive_workspace_path,project_name, isContinue):
        print('\n\n ==============build=============')

        if len(archive_workspace_path) == 0:
            print('\n\n ========archive_workspace_path is nil=============')
            return

        if len(project_name)== 0:
            project_name = 'ztjyyd'

        archive_workspace_path = self.modifyFilePath(archive_workspace_path)
        export_directory  = self.modifyFilePath(export_directory)

        start = time.time()
        clean_cmd = 'xcodebuild build -workspace %s%s.xcworkspace -scheme %s ' % (
            archive_workspace_path, project_name, project_name)
        clean_command_run = subprocess.Popen(clean_cmd, shell=True)
        clean_command_run.wait()
        end = time.time()
        # Code码
        clean_result_code = clean_command_run.returncode
        if clean_result_code != 0:
            print("=======build失败,用时:%.2f秒=======" % (end - start))
        else:
            print("=======build成功,用时:%.2f秒=======" % (end - start))
            if isContinue :
                if len(export_directory) == 0:
                    print('\n\n ========export_directory is nil=============')
                    return
                    self.archive(export_directory, archive_workspace_path,project_name, isContinue)


    def archive(self, export_directory, archive_workspace_path,project_name, isContinue):
        print("\n\n===========开始archive操作===========")

        if len(archive_workspace_path) == 0:
            print('\n\n ========archive_workspace_path is nil=============')
            return
        if len(export_directory) == 0:
            print('\n\n ========export_directory is nil=============')
            return
        archive_workspace_path = self.modifyFilePath(archive_workspace_path)
        export_directory = self.modifyFilePath(export_directory)

        start = time.time()
        archive_cmd = 'xcodebuild archive -workspace %s%s.xcworkspace -scheme %s -configuration Release -archivePath %s%s' % (
            archive_workspace_path, project_name, project_name, export_directory,project_name )
        archive_command_run = subprocess.Popen(archive_cmd, shell=True)
        archive_command_run.wait()
        end = time.time()
        # Code码
        archive_result_code = archive_command_run.returncode
        if archive_result_code != 0:
            print("=======archive失败,用时:%.2f秒=======" % (end - start))
        else:
            print("=======archive成功,用时:%.2f秒=======" % (end - start))
            if isContinue:
                self.export(export_directory, archive_workspace_path,project_name, isContinue)


    def export(self, export_directory, archive_workspace_path,project_name, isContinue):
        print("\n\n===========开始export操作===========")
        print("\n\n==========请你耐心等待一会~===========")

        if len(archive_workspace_path) == 0:
            print('\n\n ========archive_workspace_path is nil=============')
            return
        if len(export_directory) == 0:
            print('\n\n ========export_directory is nil=============')
            return
        archive_workspace_path = self.modifyFilePath(archive_workspace_path)
        export_directory  = self.modifyFilePath(export_directory)

        start = time.time()
        export_command = 'xcodebuild -exportArchive -archivePath %s%s.xcarchive -exportPath %s%s -exportOptionsPlist %s' % (
            export_directory, project_name, export_directory, project_name,exportOptionsPath)
        export_command_run = subprocess.Popen(export_command, shell=True)
        export_command_run.wait()
        end = time.time()
        export_result_code = export_command_run.returncode
        if export_result_code != 0:
            print("=======导出IPA失败,用时:%.2f秒=======" % (end - start))
        else:
            print("=======导出IPA成功,用时:%.2f秒=======" % (end - start))
            if isContinue:
                self.upload()
            # 删除archive.xcarchive文件
            # subprocess.call(['rm', '-rf', '%s/%s.xcarchive' % (archive_workspace_path, export_directory)])

    def upload(self, export_directory, project_name, isContinue):
        print("\n\n===========开始upload操作===========")
        print("\n\n==========请你耐心等待一会~===========")

        if len(export_directory) == 0:
            print('\n\n ========export_directory is nil=============')
            return
        export_directory  = self.modifyFilePath(export_directory)

        start = time.time()
        login_command = 'fir login c9c2e2f76f14c4753a9901e53e7f5888'
        login_command_run = subprocess.Popen(login_command, shell=True)
        login_command_run.wait()

        update_command ='fir publish %s%s/%s.ipa' % (export_directory, project_name,project_name)
        update_command_run = subprocess.Popen(update_command, shell=True)
        update_command_run.wait()
        update_result_code = update_command_run.returncode
        end = time.time()

        if update_result_code != 0:
            print("=======upload 失败,用时:%.2f秒=======" % (end - start))
        else:
            print("=======upload,用时:%.2f秒=======" % (end - start))
            if isContinue:
                self.deleteFile(export_directory,project_name )


    def deleteFile(self,export_directory, project_name):
        print("\n\n===========开始删除文件操作===========")

        if len(export_directory) == 0:
            print('\n\n ========export_directory is nil=============')
            return

        export_directory  = self.modifyFilePath(export_directory)

        start = time.time()
        delete_file_run = subprocess.call(['rm', '-rf', '%s%s' % (export_directory, project_name)])
        delete_file_run2 = subprocess.call(['rm', '-rf', '%s%s.xcarchive' % (export_directory, project_name)])
        end = time.time()
        if delete_file_run != 0:
            print("=======删除文件 失败,用时:%.2f秒=======" % (end - start))
        else:
            print("=======删除文件,用时:%.2f秒=======" % (end - start))


    def textAction(self, a,b,c):
        print("\n\n===========only test===========")
        print("a===%s \n b====%s \n   c=====%s " % (a,b,c))

        print(a[7:])





def main():
    # buildWorkspace()
    archive = AutoArchive()
    # archive.deleteFile()
    print('main')
    # gui = AUTOGUI()
    # gui.setUpViews()

    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = archive_test.Ui_MainWindow()
    ui.setupUi(MainWindow)


    ui.pushButton.clicked.connect(lambda: archive.build(ui.lineEdit_3.toPlainText(),ui.lineEdit.toPlainText(),ui.lineEdit_2.text(),True))
    ui.pushButton_2.clicked.connect(lambda: archive.clean('',ui.lineEdit.toPlainText(),ui.lineEdit_2.text(),False))  #clean
    ui.pushButton_3.clicked.connect(lambda: archive.build('',ui.lineEdit.toPlainText(),ui.lineEdit_2.text(),False))  #build
    ui.pushButton_4.clicked.connect(lambda: archive.deleteFile(ui.lineEdit_3.toPlainText(),ui.lineEdit_2.text()))  #delete
    ui.pushButton_5.clicked.connect(lambda: archive.upload(ui.lineEdit_3.toPlainText(),ui.lineEdit_2.text(),False))  #upload
    ui.pushButton_6.clicked.connect(lambda: archive.export(ui.lineEdit_3.toPlainText(),ui.lineEdit.toPlainText(),ui.lineEdit_2.text(),False))  #export
    ui.pushButton_7.clicked.connect(lambda: archive.archive(ui.lineEdit_3.toPlainText(),ui.lineEdit.toPlainText(),ui.lineEdit_2.text(),False))  #archive


    MainWindow.show()
    sys.exit(app.exec_())








if __name__ == '__main__' :
    main()